package kuoge.practice.concurrent.aqs.injvm;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CountDownSimple {
    private static final int CONCURRENT_THREAD_SIZE = 10;
    private static final CountDownLatch START_GATE_LATCH = new CountDownLatch(1);
    private static final CountDownLatch END_GATE_LATCH = new CountDownLatch(CONCURRENT_THREAD_SIZE);
    private static final Executor executor = Executors.newFixedThreadPool(CONCURRENT_THREAD_SIZE);

    public static void main(String[] args) {
        final Runnable runnable = () -> {
            try {
                // 等待main线程执行 countDown()后才执行
                START_GATE_LATCH.await(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "_" + System.currentTimeMillis());
            END_GATE_LATCH.countDown();
        };

        for (int i = 0;i < CONCURRENT_THREAD_SIZE;i++) {
            executor.execute(runnable);
        }
        // 模拟并发执行
        System.out.println("ready to execute");
        START_GATE_LATCH.countDown();
        System.out.println("after to execute");
        try {
            END_GATE_LATCH.await(15, TimeUnit.SECONDS);
            System.exit(0);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
